/**
 * @description 创建增强的model
 */
import { SERVICES_KEY, UPDATE_REDUCER, UPDATE_LOADING_REDUCER } from './constants';
import createSubscriptions from './subscriptions';

const createModel = ({
  state = {},
  reducers = {},
  subscriptions = {},
  subs,
  effects,
  namespace,
  ...restProps
}) => {
  /**
   * 扩展reducers 为update effect提供支持
   */
  const enhanceReducers = {
    ...reducers,
    [UPDATE_REDUCER](state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    [UPDATE_LOADING_REDUCER](state = {}, { payload }) {
      return {
        ...state,
        loading: {
          ...state.loading,
          ...payload,
        },
      };
    },
  };
  /**
   * 为subscriptions 提供一个subs的别名
   */
  const _subscriptions = subs || subscriptions;

  return {
    state: {
      loading: {},
      ...state,
    },
    reducers: enhanceReducers,
    subscriptions: createSubscriptions(_subscriptions),
    // feat: 额外的services用于server装饰器
    [SERVICES_KEY]: (restProps || {})[SERVICES_KEY],
    namespace,
    effects,
  };
};

export default createModel;
